package com.njtoyo.taxi.admin.rest.readfile.taxis;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.library.common.util.CopyUtil;
import com.njtoyo.taxi.admin.logic.business.TaxisLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.Taxi;
import com.njtoyo.taxi.admin.rest.wrapper.business.taxis.RegisterBatchWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class RegisterBatchListener extends AnalysisEventListener<RegisterBatchData> {
    @Autowired
    private OperationRecordHelper operationRecordHelper;
    private static final Logger LOGGER = LoggerFactory.getLogger(RegisterBatchListener.class);

    private final RegisterBatchResult result = new RegisterBatchResult();
    private final TaxisLogic registerBatchLogic;
    private final RegisterBatchWrapper wrapper;
    private final List<Taxi> successResult = new ArrayList<>();
    private final List<RegisterBatchResult.FailData> failResult = new ArrayList<>();

    public RegisterBatchListener(TaxisLogic registerBatchLogic, RegisterBatchWrapper wrapper) {
        this.registerBatchLogic = registerBatchLogic;
        this.wrapper = wrapper;
    }

    @Override
    public void invoke(RegisterBatchData RegisterBatchData, AnalysisContext analysisContext) {
        this.result.setUploadCount(this.result.getUploadCount() + 1);
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(RegisterBatchData));
        try {
            String serialNumber = RegisterBatchData.getSerialNumber();
            String plateNumber = RegisterBatchData.getPlateNumber();
            Long companyId = wrapper.getCompanyId();
            Taxi taxi = registerBatchLogic.registerBatch(plateNumber, serialNumber, companyId);
            this.successResult.add(taxi);
            this.result.setSuccessCount(this.result.getSuccessCount() + 1);
        } catch (Exception e) {
            RegisterBatchResult.FailData failData = CopyUtil.copy(RegisterBatchData, RegisterBatchResult.FailData.class);
            failData.setMessage(e.getMessage());
            this.failResult.add(failData);
            this.result.setFailCount(this.result.getFailCount() + 1);
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.result.setSuccessResult(this.successResult);
        this.result.setFailResult(this.failResult);
    }

    public RegisterBatchResult getResult() {
        return result;
    }
}





